'use client';

import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Tag, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  InputNumber,
  Select,
  Upload,
  message,
  Popconfirm,
  Image,
  Switch
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
  EyeOutlined
} from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import { request } from '@/utils/request';

const { Option } = Select;
const { TextArea } = Input;

interface Product {
  id: number;
  name: string;
  categoryId: number;
  categoryName: string;
  description: string;
  origin: string;
  species: string;
  processingMethod: string;
  grade: string;
  price: number;
  stockQuantity: number;
  unit: string;
  weightPerUnit: number;
  imageUrl: string;
  imageUrls: string[];
  status: string;
  createdAt: string;
  updatedAt: string;
  inStock: boolean;
}

interface Category {
  id: number;
  name: string;
  children?: Category[];
}

const AdminProducts: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [searchForm] = Form.useForm();
  const [productForm] = Form.useForm();

  useEffect(() => {
    fetchProducts();
    fetchCategories();
  }, [pagination.current, pagination.pageSize]);

  const fetchProducts = async (searchParams?: any) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: (pagination.current - 1).toString(),
        size: pagination.pageSize.toString(),
        ...searchParams,
      });

      const response = await request.get(`/products?${params.toString()}`);
      
      if (response.code === 200) {
        setProducts(response.data.content || []);
        setPagination(prev => ({ 
          ...prev, 
          total: response.data.totalElements || 0 
        }));
      } else {
        message.error(response.message || '获取产品列表失败');
      }
    } catch (error: any) {
      message.error(error.message || '获取产品列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await request.get('/categories/tree');
      
      if (response.code === 200) {
        // 将树形结构的分类转换为扁平结构
        const flattenCategories = (categories: any[], result: any[] = []) => {
          categories.forEach(category => {
            result.push({
              id: category.id,
              name: category.name
            });
            if (category.children && category.children.length > 0) {
              flattenCategories(category.children, result);
            }
          });
          return result;
        };
        
        const flatCategories = flattenCategories(response.data || []);
        setCategories(flatCategories);
      } else {
        message.error(response.message || '获取分类失败');
      }
    } catch (error: any) {
      message.error(error.message || '获取分类失败');
    }
  };

  const handleAdd = () => {
    setEditingProduct(null);
    productForm.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    productForm.setFieldsValue({
      ...product,
      categoryId: product.categoryId,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await request.delete(`/products/${id}`);
      
      if (response.code === 200) {
        message.success('产品删除成功');
        fetchProducts();
      } else {
        message.error(response.message || '删除产品失败');
      }
    } catch (error: any) {
      message.error(error.message || '删除产品失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      let response;
      
      if (editingProduct) {
        // 更新产品
        response = await request.put(`/products/${editingProduct.id}`, values);
        message.success('产品更新成功');
      } else {
        // 创建产品
        response = await request.post('/products', values);
        message.success('产品创建成功');
      }
      
      if (response.code === 200) {
        setModalVisible(false);
        fetchProducts();
      } else {
        message.error(response.message || '保存产品失败');
      }
    } catch (error: any) {
      message.error(error.message || '保存产品失败');
    }
  };

  const handleSearch = (values: any) => {
    fetchProducts(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchProducts();
  };

  const handleStatusChange = async (id: number, status: string) => {
    try {
      const response = await request.put(`/products/${id}`, { status });
      
      if (response.code === 200) {
        message.success('状态更新成功');
        fetchProducts();
      } else {
        message.error(response.message || '状态更新失败');
      }
    } catch (error: any) {
      message.error(error.message || '状态更新失败');
    }
  };

  const columns = [
    {
      title: '图片',
      dataIndex: 'imageUrl',
      key: 'imageUrl',
      width: 80,
      render: (imageUrl: string) => (
        <Image
          width={50}
          height={50}
          src={imageUrl}
          alt="产品图片"
          fallback="/images/default-product.png"
          style={{ objectFit: 'cover', borderRadius: '4px' }}
        />
      ),
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 100,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: number) => `¥${price.toFixed(2)}`,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: 80,
    },
    {
      title: '库存',
      dataIndex: 'stockQuantity',
      key: 'stockQuantity',
      width: 80,
      render: (stock: number) => (
        <span style={{ color: stock < 10 ? '#ff4d4f' : '#000' }}>
          {stock}
        </span>
      ),
    },
    {
      title: '产地',
      dataIndex: 'origin',
      key: 'origin',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: Product) => (
        <Switch
          checked={status === 'ACTIVE'}
          onChange={(checked) => handleStatusChange(record.id, checked ? 'ACTIVE' : 'INACTIVE')}
          checkedChildren="上架"
          unCheckedChildren="下架"
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (text: any, record: Product) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
          >
            查看
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个产品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              size="small" 
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout 
      selectedKey="2" 
      breadcrumbItems={[{ title: '产品管理' }]}
    >
      <div style={{ padding: '24px' }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '24px' 
        }}>
          <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
            产品管理
          </h1>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加产品
          </Button>
        </div>

        {/* 搜索表单 */}
        <Card style={{ marginBottom: '24px' }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
          >
            <Form.Item name="name" label="产品名称">
              <Input placeholder="请输入产品名称" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name="categoryId" label="产品分类">
              <Select placeholder="请选择分类" style={{ width: 150 }} allowClear>
                {categories.map(category => (
                  <Option key={category.id} value={category.id}>
                    {category.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
                <Option value="ACTIVE">上架</Option>
                <Option value="INACTIVE">下架</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 产品列表 */}
        <Card>
          <Table
            columns={columns}
            dataSource={products}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination(prev => ({
                  ...prev,
                  current: page,
                  pageSize: pageSize || prev.pageSize,
                }));
              },
            }}
            scroll={{ x: 1400 }}
          />
        </Card>

        {/* 产品编辑模态框 */}
        <Modal
          title={editingProduct ? '编辑产品' : '添加产品'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => productForm.submit()}
          width={800}
          destroyOnClose
        >
          <Form
            form={productForm}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="name"
              label="产品名称"
              rules={[{ required: true, message: '请输入产品名称' }]}
            >
              <Input placeholder="请输入产品名称" />
            </Form.Item>
            
            <Form.Item
              name="categoryId"
              label="产品分类"
              rules={[{ required: true, message: '请选择产品分类' }]}
            >
              <Select placeholder="请选择分类">
                {categories.map(category => (
                  <Option key={category.id} value={category.id}>
                    {category.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="description"
              label="产品描述"
              rules={[{ required: true, message: '请输入产品描述' }]}
            >
              <TextArea rows={3} placeholder="请输入产品描述" />
            </Form.Item>

            <Form.Item
              name="price"
              label="价格"
              rules={[{ required: true, message: '请输入价格' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                step={0.01}
                precision={2}
                placeholder="请输入价格"
                addonAfter="元"
              />
            </Form.Item>

            <Form.Item
              name="unit"
              label="单位"
              rules={[{ required: true, message: '请输入单位' }]}
            >
              <Input placeholder="如：kg、只、包等" />
            </Form.Item>

            <Form.Item
              name="stockQuantity"
              label="库存数量"
              rules={[{ required: true, message: '请输入库存数量' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                placeholder="请输入库存数量"
              />
            </Form.Item>

            <Form.Item
              name="origin"
              label="产地"
              rules={[{ required: true, message: '请输入产地' }]}
            >
              <Input placeholder="请输入产地" />
            </Form.Item>

            <Form.Item
              name="species"
              label="品种"
            >
              <Input placeholder="请输入品种" />
            </Form.Item>

            <Form.Item
              name="processingMethod"
              label="加工方式"
            >
              <Input placeholder="请输入加工方式" />
            </Form.Item>

            <Form.Item
              name="grade"
              label="等级"
            >
              <Input placeholder="请输入等级" />
            </Form.Item>

            <Form.Item
              name="weightPerUnit"
              label="单位重量"
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                step={0.001}
                precision={3}
                placeholder="请输入单位重量"
                addonAfter="kg"
              />
            </Form.Item>

            <Form.Item
              name="imageUrl"
              label="产品图片"
            >
              <Input placeholder="请输入图片URL" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default AdminProducts;